from datetime import datetime

from fastapi import APIRouter, Request
from typing import Dict, List, Any
from pydantic import BaseModel, Field
from utils.logger import Logger
from utils.constants import ErrorCode, AGENT_TYPES
from auxiliary_agents.health_monitor import health_check_agent
from distributed import circuit_breaker_manager, rate_limiter
from config import base_config, middleware_config

# 初始化路由和日志
status_router = APIRouter()
logger = Logger.get_logger(agent_name="status_router")

class SystemStatusResponse(BaseModel):
    """系统状态响应模型"""
    code: int = Field(ErrorCode.SUCCESS.value, description="错误码")
    message: str = Field("success", description="状态信息")
    data: Dict[str, Any] = Field(..., description="状态数据")
    request_id: str = Field(..., description="请求ID")

@status_router.get("/status", summary="系统状态监控接口")
async def get_system_status(request: Request):
    """获取系统整体状态（Agent健康、限流、中间件、配置等）"""
    # 安全获取request_id，如果不存在则生成一个临时ID
    try:
        request_id = request.state.request_id
    except AttributeError:
        # 生成一个简单的UUID作为临时请求ID
        import uuid
        request_id = str(uuid.uuid4())
    logger.debug(f"获取系统状态: request_id={request_id}")

    # 1. 收集各Agent健康状态
    agent_health_status: Dict[str, List[Dict]] = {}
    for agent_type in AGENT_TYPES:
        agent_health_status[agent_type] = health_check_agent.get_healthy_agents(agent_type)

    # 2. 收集熔断器状态
    breaker_status = circuit_breaker_manager.get_all_breaker_states()

    # 3. 收集限流统计（简化：获取当前全局限流剩余次数）
    rate_limit_status = {
        "global": rate_limiter.check("global"),
        "user_sample": rate_limiter.check("user", identifier="user_001"),  # 示例用户
        "agent_sample": rate_limiter.check("agent", identifier="text_qa_001")  # 示例Agent
    }

    # 4. 收集中间件状态（使用安全的方式访问配置）
    middleware_status = {}
    
    # Redis状态
    try:
        redis_config = getattr(middleware_config, 'redis', {})
        middleware_status["redis"] = {
            "host": getattr(redis_config, 'host', 'localhost'),
            "port": getattr(redis_config, 'port', 6379),
            "db": getattr(redis_config, 'db', 0),
            "connected": health_check_agent.check_redis_health() if hasattr(health_check_agent, 'check_redis_health') else True
        }
    except Exception as e:
        logger.warning(f"获取Redis配置失败: {e}")
        middleware_status["redis"] = {
            "host": "unknown",
            "port": 0,
            "db": 0,
            "connected": False
        }
    
    # Milvus状态
    try:
        milvus_config = getattr(middleware_config, 'milvus', {})
        middleware_status["milvus"] = {
            "host": getattr(milvus_config, 'host', 'localhost'),
            "port": getattr(milvus_config, 'port', 19530),
            "collection": getattr(milvus_config, 'collection_name', 'default'),
            "connected": health_check_agent.check_milvus_health() if hasattr(health_check_agent, 'check_milvus_health') else False
        }
    except Exception as e:
        logger.warning(f"获取Milvus配置失败: {e}")
        middleware_status["milvus"] = {
            "host": "unknown",
            "port": 0,
            "collection": "unknown",
            "connected": False
        }
    
    # MinIO状态
    try:
        minio_config = getattr(middleware_config, 'minio', {})
        middleware_status["minio"] = {
            "endpoint": getattr(minio_config, 'endpoint', 'localhost:9000'),
            "bucket": getattr(minio_config, 'bucket_name', 'default'),
            "connected": health_check_agent.check_minio_health() if hasattr(health_check_agent, 'check_minio_health') else False
        }
    except Exception as e:
        logger.warning(f"获取MinIO配置失败: {e}")
        middleware_status["minio"] = {
            "endpoint": "unknown",
            "bucket": "unknown",
            "connected": False
        }

    # 5. 收集系统配置信息（脱敏）
    try:
        system_config = {
            "project_name": getattr(base_config, 'project_name', 'MAESS'),
            "version": getattr(base_config, 'project_version', '1.0.0'),
            "env": getattr(base_config, 'env', 'development'),
            "api_prefix": getattr(base_config, 'api_prefix', '/api/v1'),
            "cache_ttl": getattr(base_config, 'cache_default_ttl', 3600),
            "auth_enabled": getattr(base_config, 'is_prod', False)  # 生产环境默认启用鉴权
        }
    except Exception as e:
        logger.warning(f"获取系统配置失败: {e}")
        system_config = {
            "project_name": "MAESS",
            "version": "1.0.0",
            "env": "development",
            "api_prefix": "/api/v1",
            "cache_ttl": 3600,
            "auth_enabled": False
        }

    # 6. 计算Dashboard需要的简化统计数据
    total_active_agents = sum(len(agents) for agents in agent_health_status.values())
    
    return {
        "code": ErrorCode.SUCCESS.value,
        "message": "success",
        "data": {
            # Dashboard需要的核心统计数据
            "active_agents": total_active_agents,
            "queue_length": 0,  # 简化：当前队列为空
            "system_load": 15,  # 简化：模拟15%的系统负载
            "response_time": 120,  # 简化：模拟120ms响应时间
            
            # 详细数据（供其他用途）
            "system_config": system_config,
            "agent_health": agent_health_status,
            "circuit_breaker": breaker_status,
            "rate_limit": rate_limit_status,
            "middleware": middleware_status,
            "timestamp": datetime.now().strftime(getattr(base_config, 'datetime_format', '%Y-%m-%d %H:%M:%S'))
        },
        "request_id": request_id
    }